<template>
  <div class="site-popup-manage">
    <div class="page-header">
      <h2>站点弹窗管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="info" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- Tab页导航 -->
    <el-tabs v-model="activeTab" type="card" class="popup-tabs">
      <el-tab-pane label="站点优惠券配置" name="coupon-config">
        <CouponConfigTab
          :sites="sites"
          :coupons="coupons"
          :configs="couponConfigs"
          :popupRules="popupRules"
          :loading="loading"
          @refresh="loadCouponConfigs"
          @create="openCouponConfigDialog"
          @edit="editCouponConfig"
          @delete="deleteCouponConfig"
        />
      </el-tab-pane>

      <el-tab-pane label="弹窗规则设置" name="popup-rules">
        <PopupRulesTab
          :rules="popupRules"
          :loading="loading"
          @refresh="loadPopupRules"
          @create="openPopupRuleDialog"
          @edit="editPopupRule"
          @delete="deletePopupRule"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 站点优惠券配置弹窗 -->
    <el-dialog
      v-model="couponConfigDialogVisible"
      :title="couponConfigEditMode === 'add' ? '新增站点优惠券配置' : '编辑站点优惠券配置'"
      width="800px"
      :close-on-click-modal="false"
    >
      <CouponConfigForm
        :form="couponConfigForm"
        :sites="sites"
        :coupons="coupons"
        :popupRules="popupRules"
        @submit="handleCouponConfigSubmit"
        @cancel="couponConfigDialogVisible = false"
      />
    </el-dialog>

    <!-- 弹窗规则弹窗 -->
    <el-dialog
      v-model="popupRuleDialogVisible"
      :title="popupRuleEditMode === 'add' ? '新增弹窗规则' : '编辑弹窗规则'"
      width="900px"
      :close-on-click-modal="false"
    >
      <PopupRuleFormComponent
        :form="popupRuleForm"
        :sites="sites"
        @submit="handlePopupRuleSubmit"
        @cancel="popupRuleDialogVisible = false"
      />
    </el-dialog>

    <!-- 弹窗样式弹窗 -->
    <!-- <el-dialog
      v-model="popupStyleDialogVisible"
      :title="popupStyleEditMode === 'add' ? '新增弹窗样式' : '编辑弹窗样式'"
      width="1000px"
      :close-on-click-modal="false"
    >
      <PopupStyleFormComponent
        :form="popupStyleForm"
        :sites="sites"
        @submit="handlePopupStyleSubmit"
        @cancel="popupStyleDialogVisible = false"
      />
    </el-dialog> -->

    <!-- 弹窗预览弹窗 -->
    <!-- <el-dialog
      v-model="previewDialogVisible"
      title="弹窗预览"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="preview-container">
        <div v-html="previewHtml" class="preview-content"></div>
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Download } from '@element-plus/icons-vue'
import SitePopupService from '@/services/sitePopupService'
import type {
  Site,
  Coupon,
  SiteCouponConfig,
  PopupRule,
  PopupStyle,
  PopupRecord,
  PopupStats,
  SiteCouponConfigForm
} from '@/types/sitePopup'
import type {
  PopupRuleForm,
  PopupStyleForm
} from '@/types/sitePopup'

// 导入子组件
import CouponConfigTab from './components/CouponConfigTab.vue'
import PopupRulesTab from './components/PopupRulesTab.vue'
import CouponConfigForm from './components/CouponConfigForm.vue'
import PopupRuleFormComponent from './components/PopupRuleForm.vue'

// 响应式数据
const activeTab = ref('coupon-config')
const loading = ref(false)

// 基础数据
const sites = ref<Site[]>([])
const coupons = ref<Coupon[]>([])

// 各Tab页数据
const couponConfigs = ref<SiteCouponConfig[]>([])
const popupRules = ref<PopupRule[]>([])

// 弹窗控制
const couponConfigDialogVisible = ref(false)
const popupRuleDialogVisible = ref(false)

// 编辑模式
const couponConfigEditMode = ref<'add' | 'edit'>('add')
const popupRuleEditMode = ref<'add' | 'edit'>('add')
const popupStyleEditMode = ref<'add' | 'edit'>('add')

// 表单数据
const couponConfigForm = reactive<SiteCouponConfigForm>({
  siteId: '',
  couponId: '',
  popupRuleId: '',
  status: 'active',
  showFrequency: 'once',
  userScope: 'all',
  userTags: []
})

const popupRuleForm = reactive<PopupRuleForm>({
  name: '',
  description: '',
  triggerType: 'delay',
  delaySeconds: 5,
  popupTitle: '',
  popupContent: '',
  buttonText: '立即领取',
  popupStyle: 'default',
  showConditions: {
    userType: 'all',
    deviceType: 'mobile',
    dayOfWeek: [1, 2, 3, 4, 5, 6, 7],
    timeRange: {
      start: '',
      end: ''
    }
  },
  frequencyLimit: {
    maxShows: 1,
    period: 'session'
  },
  status: 'active'
})

// 预览HTML
const previewHtml = ref('')

// 生命周期
onMounted(() => {
  loadInitialData()
})

// 加载初始数据
const loadInitialData = async () => {
  try {
    loading.value = true
    await Promise.all([
      loadSites(),
      loadCoupons(),
      loadCouponConfigs(),
      loadPopupRules()
    ])
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载站点列表
const loadSites = async () => {
  try {
    sites.value = await SitePopupService.getSites()
  } catch (error) {
    console.error('加载站点失败:', error)
  }
}

// 加载优惠券列表
const loadCoupons = async () => {
  try {
    coupons.value = await SitePopupService.getCoupons()
  } catch (error) {
    console.error('加载优惠券失败:', error)
  }
}

// 加载站点优惠券配置
const loadCouponConfigs = async () => {
  try {
    const result = await SitePopupService.getSiteCouponConfigs()
    couponConfigs.value = result.data
  } catch (error) {
    console.error('加载站点优惠券配置失败:', error)
  }
}

// 加载弹窗规则
const loadPopupRules = async () => {
  try {
    const result = await SitePopupService.getPopupRules()
    popupRules.value = result.data
  } catch (error) {
    console.error('加载弹窗规则失败:', error)
  }
}

// 刷新数据
const refreshData = () => {
  loadInitialData()
}

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

// 站点优惠券配置相关方法
const openCouponConfigDialog = (mode: 'add' | 'edit', config?: SiteCouponConfig) => {
  couponConfigEditMode.value = mode
  if (mode === 'edit' && config) {
    Object.assign(couponConfigForm, {
      siteId: config.siteId,
      couponId: config.couponId,
      popupRuleId: config.popupRuleId || '',
      status: config.status,
      showFrequency: config.showFrequency,
      userScope: config.userScope,
      userTags: config.userTags || []
    })
  } else {
    Object.assign(couponConfigForm, {
      siteId: '',
      couponId: '',
      popupRuleId: '',
      status: 'active',
      showFrequency: 'once',
      userScope: 'all',
      userTags: []
    })
  }
  couponConfigDialogVisible.value = true
}

const editCouponConfig = (config: SiteCouponConfig) => {
  openCouponConfigDialog('edit', config)
}

const deleteCouponConfig = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个配置吗？', '确认删除', {
      type: 'warning'
    })

    await SitePopupService.deleteSiteCouponConfig(id)
    ElMessage.success('删除成功')
    loadCouponConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

const handleCouponConfigSubmit = async (form: SiteCouponConfigForm) => {
  try {
    if (couponConfigEditMode.value === 'add') {
      await SitePopupService.createSiteCouponConfig(form)
      ElMessage.success('创建成功')
    } else {
      // 编辑模式
      const configId = couponConfigs.value.find(c => 
        c.siteId === form.siteId && c.couponId === form.couponId
      )?.id
      
      if (configId) {
        await SitePopupService.updateSiteCouponConfig(configId, form)
        ElMessage.success('更新成功')
      } else {
        ElMessage.error('找不到要更新的配置')
        return
      }
    }

    couponConfigDialogVisible.value = false
    loadCouponConfigs()
  } catch (error) {
    ElMessage.error('操作失败')
    console.error('操作失败:', error)
  }
}

// 弹窗规则相关方法
const openPopupRuleDialog = (mode: 'add' | 'edit', rule?: PopupRule) => {
  popupRuleEditMode.value = mode
  if (mode === 'edit' && rule) {
    Object.assign(popupRuleForm, {
      name: rule.name,
      description: rule.description,
      triggerType: rule.triggerType,
      delaySeconds: rule.delaySeconds,
      popupTitle: rule.popupTitle,
      popupContent: rule.popupContent,
      buttonText: rule.buttonText,
      popupStyle: rule.popupStyle,
      showConditions: rule.showConditions,
      frequencyLimit: rule.frequencyLimit,
      status: rule.status
    })
  } else {
    Object.assign(popupRuleForm, {
      name: '',
      description: '',
      triggerType: 'delay',
      delaySeconds: 5,
      popupTitle: '',
      popupContent: '',
      buttonText: '立即领取',
      popupStyle: 'default',
      showConditions: {
        userType: 'all',
        deviceType: 'mobile',
        dayOfWeek: [1, 2, 3, 4, 5, 6, 7]
      },
      frequencyLimit: {
        maxShows: 1,
        period: 'session'
      },
      status: 'active'
    })
  }
  popupRuleDialogVisible.value = true
}

const editPopupRule = (rule: PopupRule) => {
  openPopupRuleDialog('edit', rule)
}

const deletePopupRule = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个规则吗？', '确认删除', {
      type: 'warning'
    })

    await SitePopupService.deletePopupRule(id)
    ElMessage.success('删除成功')
    loadPopupRules()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

const handlePopupRuleSubmit = async (form: PopupRuleForm) => {
  try {
    if (popupRuleEditMode.value === 'add') {
      await SitePopupService.createPopupRule(form)
      ElMessage.success('创建成功')
    } else {
      // 编辑模式
      const ruleId = popupRules.value.find(r => r.name === form.name)?.id
      
      if (ruleId) {
        await SitePopupService.updatePopupRule(ruleId, form)
        ElMessage.success('更新成功')
      } else {
        ElMessage.error('找不到要更新的规则')
        return
      }
    }

    popupRuleDialogVisible.value = false
    loadPopupRules()
  } catch (error) {
    ElMessage.error('操作失败')
    console.error('操作失败:', error)
  }
}

// 导出统计数据
const exportStats = () => {
  ElMessage.info('导出功能开发中...')
}
</script>

<style scoped>
.site-popup-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.popup-tabs {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
}

.preview-content {
  position: relative;
}

.preview-content .popup-preview {
  position: relative !important;
  transform: none !important;
  top: auto !important;
  left: auto !important;
  right: auto !important;
  bottom: auto !important;
}
</style>
